﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CashOrCard.Models;
using CashOrCard.Repository;
using CashOrCard.Extensions;
using CashOrCard.Helper;

namespace CashOrCard.Controllers
{
    public class PromotionCommentController : Controller
    {
        private readonly IBaseRepository<PromotionComment> _promCommRep;
        private readonly IBaseRepository<Promotion> _promRep;
        private readonly IBaseRepository<FakeComment> _fcRep;
        public PromotionCommentController(IBaseRepository<PromotionComment> promCommRep, 
                                          IBaseRepository<Promotion> promRep,
                                          IBaseRepository<FakeComment> fcRep)
        {
            this._promCommRep = promCommRep;
            this._promRep = promRep;
            this._fcRep = fcRep;
        }

        public ActionResult Index(int? promotionId)
        {
            TempData["promotionId"] = promotionId;
            var prmomotion = _promRep.LoadEntities(x => x.PromotionId == promotionId).FirstOrDefault();
            ViewBag.promotion = prmomotion;
            return View();
        }

        public ActionResult GetAllComments()
        {
            int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]);
            int pageSize = Request["rows"] == null ? 10 : int.Parse(Request["rows"]);
            int promotionId = Request["promotionId"] == null ? -1 : Convert.ToInt32(Request["promotionId"]);
            int total = 0;
            IQueryable<PromotionComment> promCommList = null;
            if (promotionId > -1)
            {
                var prmomotion = _promRep.LoadEntities(x => x.PromotionId == promotionId).FirstOrDefault();
                if (prmomotion != null)
                    promCommList = prmomotion.PromotionComments.Where(x => x.IsEnable).AsQueryable();
                //promCommList = _promCommRep.LoadPagerEntities(pageSize, pageIndex, out total, x => x.Promotions.Where(p => p.PromotionId == promotionId).FirstOrDefault().PromotionId == promotionId, true, x => x.PromotionCommentId);
            }
            else
            {
                promCommList = _promCommRep.LoadPagerEntities(pageSize, pageIndex, out total, x => x.IsEnable, true, x => x.PromotionCommentId);
            }
            var list = (from pc in promCommList
                        select new { PromotionCommentId = pc.PromotionCommentId,
                                     PromotionCommentBody = pc.PromotionCommentBody,
                                     CreateDate = pc.CreateDate,
                                     CommentUser = string.Format("{0} {1}", pc.User.FirstName, pc.User.LastName)
                        }).ToList();
            var result = new { total = total, rows = list };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult DeletePC(int id)
        {
            var pc = _promCommRep.Get(id);
            pc.IsEnable = false;
            var result = _promCommRep.UpdateEntities(pc);
            if (result)
                return Content("success");
            else
                return Content("Some errors occured.");
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "fcmanagement_access", ErrorView = "PermissionDenied")]
        public ActionResult FackComment()
        {
            return View("FakeComments");
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "fcmanagement_access", ErrorView = "PermissionDenied")]
        public ActionResult GetAllFC(string FCStatus)
        {
            int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]);
            int pageSize = Request["rows"] == null ? 10 : int.Parse(Request["rows"]);
            int total = 0;
            IQueryable<FakeComment> fcs = null;
            string status = "all";
            if (!string.IsNullOrEmpty(FCStatus))
                status = FCStatus.ToLower();
            switch (status)
            {
                case "open":
                    fcs = _fcRep.LoadPagerEntities(pageSize, pageIndex, out total, x => x.IsEnable && !x.IsClosed ,true, x => x.FakeCommentId);
                    break;
                case "closed":
                    fcs = _fcRep.LoadPagerEntities(pageSize, pageIndex, out total, x => x.IsEnable && x.IsClosed, true, x => x.FakeCommentId);
                    break;
                default:
                    fcs = _fcRep.LoadPagerEntities(pageSize, pageIndex, out total, x => x.IsEnable, true, x => x.FakeCommentId);
                    break;
            }
            var list = (from fc in fcs
                       select new { FakeCommentId = fc.FakeCommentId, 
                                    CommentBody = fc.CommentBody,
                                    CommentUser = string.Format("{0} {1}", fc.User.FirstName, fc.User.LastName),
                                    PromotionName = fc.Promotion.PromotionName,
                                    CreateDate = fc.CreateDate,
                                    CloseDate = fc.CloseDate
                       }).ToList();
            var result = new { total = total, rows = list };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "fcmanagement_access", ErrorView = "PermissionDenied")]
        public ActionResult DeleteFC(int id)
        {
            var result = delOrCloseFC("Delete", id);
            if (result)
                return Content("success");
            else
                return Content("Some errors occured.");
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "fcmanagement_access", ErrorView = "PermissionDenied")]
        public ActionResult CloseFC(int id)
        {
            var result = delOrCloseFC("Close", id);
            if (result)
                return Content("success");
            else
                return Content("Some errors occured.");
        }

        [CashOrCardAuthorizeExtension(AllowPermissions = "fcmanagement_access", ErrorView = "PermissionDenied")]
        private bool delOrCloseFC(string type, int id)
        { 
            var fc = _fcRep.Get(id);
            if (type == "Delete")
                fc.IsEnable = false;
            else
            {
                fc.IsClosed = true;
                fc.CloseDate = DateTime.Now;
            }
            var result = _fcRep.UpdateEntities(fc);
            return result;
        }

        public ActionResult CustomerComment()
        {
            return View("CustomerComments");
        }

        public ActionResult GetAllCC(string siteName, string promName)
        {
            int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]);
            int pageSize = Request["rows"] == null ? 10 : int.Parse(Request["rows"]);
            int curUserId = Common.CurrentUser.UserId;
            int total = 0;
            var promCommList = _promCommRep.LoadPagerEntities(pageSize, pageIndex, out total, 
                                                                x =>
                                                               (string.IsNullOrEmpty(siteName) ||
                                                                x.Promotion.AdvtSite.SiteName.ToLower().Contains(siteName.ToLower()))
                                                               && (string.IsNullOrEmpty(promName) ||
                                                                x.Promotion.PromotionName.ToLower().Contains(promName.ToLower()))
                                                                && x.IsEnable && x.UserId == curUserId, true, x => x.CreateDate);
            var list = (from pc in promCommList
                        select new { PromotionCommentId = pc.PromotionCommentId,
                                     SiteName = pc.Promotion.AdvtSite.SiteName,
                                     PromotionName = pc.Promotion.PromotionName,
                                     PromotionCommentBody = pc.PromotionCommentBody,
                                     CreateDate = pc.CreateDate,
                                     
                        }).ToList();
            var result = new { total = total, rows = list };
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}
